package com.personal.system.service.impl.sys;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.personal.model.system.SysDept;
import com.personal.system.exception.GlobalException;
import com.personal.system.mapper.sys.SysDeptMapper;
import com.personal.system.service.sys.SysDeptService;
import com.personal.system.service.sys.SysRoleService;
import com.personal.system.utils.DeptHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 组织机构 服务实现类
 * </p>
 *
 * @author HD
 * @since 2022-10-29
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Resource
    private SysDeptMapper deptMapper;

    @Resource
    private SysRoleService roleService;

    @Override
    public List<SysDept> findNodes() {
        //获取所有菜单
        List<SysDept> sysDeptList = deptMapper.selectDeptList(Wrappers.emptyWrapper());
        //所有菜单数据转换要求数据格式
        List<SysDept> resultList = DeptHelper.bulidTree(sysDeptList);

        List<Tree<String>> build = TreeUtil.build(sysDeptList, "0", new TreeNodeConfig(),
                // treeNode – 源数据实体  tree – 树节点实体
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId());
                    tree.setParentId(treeNode.getParentId().toString());
                    tree.setName(treeNode.getName());
                    // 扩展属性 ...
//                    tree.putExtra("extraField", 666);
                });

        return resultList;
    }

    @Override
    public void removeDeptById(String id) {
        LambdaQueryWrapper<SysDept> qw = Wrappers.lambdaQuery(SysDept.class).eq(SysDept::getParentId, id);
        if (this.count(qw) > 0) {
            throw new GlobalException(201, "请先删除子菜单");
        }
        this.removeById(id);
    }

    @Override
    public List<Long> selectDeptListByRoleId(Long roleId) {
//        SysRole sysRole = roleService.getById(roleId);

        return baseMapper.selectDeptListByRoleId(roleId);
    }

    @Override
    public List<SysDept> selectDeptTreeList(SysDept sysDept) {

        List<SysDept> deptList = this.list();
        return DeptHelper.bulidTree(deptList);
    }

}
